from django.contrib.auth.hashers import make_password

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView,CreateView,UpdateView,DeleteView
from django.db import models
from django.http import HttpRequest, JsonResponse

from .forms import TeacherForm
from .models import Teacher
from grades.models import Grade
from django.contrib.auth.models import User

# Create your views here.
class BaseTeacherView():
    model = Teacher
    form_class = TeacherForm  # 关键：指定表单类
    success_url = reverse_lazy('teacher_list')

class TeacherListView(BaseTeacherView, ListView):
    template_name = 'teachers/teacher_list.html'
    context_object_name = 'teachers'
    paginate_by = 10

    def get_queryset(self):
        queryset = super().get_queryset()
        grade_id = self.request.GET.get('grade')
        search = self.request.GET.get('search')
        
        if grade_id:
            queryset = queryset.filter(grade_id=grade_id)
            
        if search:
            queryset = queryset.filter(
                models.Q(teacher_name__icontains=search) |
                models.Q(phone_number__icontains=search)
            )
        # 外键关系访问Grade模型的grade_number字段
        queryset = queryset.order_by('grade__grade_number', 'teacher_name')
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['grades'] = Grade.objects.all().order_by('grade_number')
        context['current_grade'] = self.request.GET.get('grade', '')
        return context

class TeacherCreateView(BaseTeacherView, CreateView):
    # form_class = TeacherForm
    template_name = 'teachers/teacher_form.html'
    context_object_name = 'tetachers'

    def form_valid(self, form):
        teacher_name = form.cleaned_data.get('teacher_name')
        phone_number = form.cleaned_data.get('phone_number')

        username = teacher_name + "_" + phone_number
        users = User.objects.filter(username=username)

        if users.exists():
            user = users.first()
        else:
            password = phone_number[-6:]
            user = User.objects.create_user(username=username, password=password)

        # 建立 Teacher 模型实例和 User 模型实例之间的关联
        form.instance.user = user
        form.save() # 保存表单数据

        return JsonResponse({'status':'success', 'messages':'录入成功！'}, status=200)
    
    def form_invalid(self, form):
        errors = form.errors.as_json() #获取所有错误信息
        return JsonResponse({'status': 'error','messages':errors,}, status=400)
        # 验证失败


class TeacherUpdateView(BaseTeacherView, UpdateView):
    # fields = ['grade','teacher_name','gender','phone_number','birthday']

    def form_valid(self, form):
        teacher = form.save(commit=False)

        if 'teacher_name' in form.changed_data or 'phone_number' in form.changed_data:
            teacher.user.username = form.cleaned_data['teacher_name'] + '_' + form.cleaned_data['phone_number']
            teacher.user.password = make_password(form.cleaned_data.get('phone_number')[-6:])
            teacher.user.save()
        teacher.save()
        return JsonResponse({'status':'success', 'messages':'更新成功！'}, status=200)
    
    def form_invalid(self, form):
        errors = form.errors.as_json() #获取所有错误信息
        return JsonResponse({'status': 'error','messages':errors,}, status=400)
        # 验证失败
    
class TeacherDeleteView(BaseTeacherView, DeleteView):
    
    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        # response = super().delete(request, *args, **kwargs)
        try:
            self.object.delete()
            return JsonResponse({'status':'success','messages':'删除成功',},status=200)
        except Exception as e:
            return JsonResponse({'status': 'error','messages':'删除失败' + str(e)},status=400)